﻿using UnityEngine;
using System.Collections;

namespace ShaderScript{
	/// 添加此脚本和以texture为反射纹理的材质就可实现镜面反射效果
	/// 对应的Shader为 Ying/Reflection/Mirror
	/// 此脚本和Sprite物体共用
	public class Mirror : MonoBehaviour {
		//SpriteRenderer spriteRenderer;
		[SerializeField] RenderTexture texture;
		Camera renderCamara;
		[SerializeField] Camera playerView;
		Material mat;
		void Start () {
			SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer> ();
			mat = spriteRenderer.sharedMaterial;
			//texture = spriteRenderer.sharedMaterial.GetTexture ("_ReflectMap");
			renderCamara = new GameObject ().AddComponent<Camera> ();
			renderCamara.CopyFrom (playerView);
			renderCamara.targetTexture = texture;
		}

		void Update () {
			Vector3 viewDir = playerView.transform.position - transform.position;
			float angle = Vector3.Angle (transform.forward, viewDir);
			float m = viewDir.magnitude * Mathf.Cos (angle/180f*Mathf.PI) * 2f;
			Vector3 renderPos = transform.position + viewDir + transform.forward * Mathf.Abs(m);
			renderCamara.transform.position = renderPos;
			renderCamara.transform.LookAt (transform.position);

			float x = transform.localScale.x;
			float y = transform.localScale.y;
			Vector3 worldPos;
			Vector3 screenPos;
			Vector4 left = new Vector4 ();
			Vector4 right = new Vector4 ();

			worldPos = transform.position + transform.right * x + transform.up * y;
			screenPos = WorldToScreenPoint (worldPos);
			left.x = screenPos.x;
			left.y = screenPos.y;

			worldPos = transform.position + transform.right * x + transform.up * (-y);
			screenPos = WorldToScreenPoint (worldPos);
			left.z = screenPos.x;
			left.w = screenPos.y;

			worldPos = transform.position + transform.right * (-x) + transform.up * y;
			screenPos = WorldToScreenPoint (worldPos);
			right.x = screenPos.x;
			right.y = screenPos.y;

			worldPos = transform.position + transform.right * (-x) + transform.up * (-y);
			screenPos = WorldToScreenPoint (worldPos);
			right.z = screenPos.x;
			right.w = screenPos.y;

			mat.SetVector ("_Left", left);
			mat.SetVector ("_Right", right);
		}
		Vector3 WorldToScreenPoint(Vector3 worldPos){
			Vector3 screenPos;
			screenPos = renderCamara.WorldToScreenPoint (worldPos);
			screenPos.x /= renderCamara.pixelWidth;
			screenPos.y /= renderCamara.pixelHeight;
			return screenPos;
		}
	}
}
